/* __auth__ : KunLin */
package com.cskaoyan.service;


import com.cskaoyan.bean.*;
import com.cskaoyan.bean.basebean.BasePageData;
import com.cskaoyan.bean.basebean.BaseParam;
import com.cskaoyan.bean.bo.CommentDeleteBO;
import com.cskaoyan.bean.bo.comment.CommentListBO;
import com.cskaoyan.bean.bo.comment.CommentReplyBO;
import com.cskaoyan.bean.vo.comment.CommentDeleteVO;
import com.cskaoyan.bean.vo.comment.CommentListVO;
import com.cskaoyan.bean.vo.comment.CommentReplyVO;
import com.cskaoyan.bean.zhao_order_bean.CommentBO;
import com.cskaoyan.bean.zhao_order_bean.Order;
import com.cskaoyan.bean.zhao_order_bean.OrderGoods;
import com.cskaoyan.exception.CommentException;
import com.cskaoyan.mapper.CommentMapper;
import com.cskaoyan.mapper.OrderGoodsMapper;
import com.cskaoyan.mapper.OrderMapper;
import com.cskaoyan.utils.CopyModuleClassUtils;
import com.cskaoyan.utils.MarketPageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import static com.cskaoyan.utils.CommonUtil.objectIsEmpty;

@Service
public class CommentServiceImpl implements CommentService{

    @Autowired
    CommentMapper commentMapper;

    @Autowired
    OrderGoodsMapper orderGoodsMapper;

    @Autowired
    OrderMapper orderMapper;

    @Override
    public CommentListVO queryAllComment(CommentListBO commentListBO) {
        PageHelper.startPage(commentListBO.getPage(), commentListBO.getLimit());
        List<Comment> commentList = queryAllComments(commentListBO);

        CommentListVO commentListVO = new CommentListVO();
        CommentListVO.DataDTO data = new CommentListVO.DataDTO();
        PageInfo<Comment> commentPageInfo = new PageInfo<>(commentList);

        data.setPages(commentPageInfo.getPages());
        data.setLimit(commentPageInfo.getPageSize());
        data.setPage(commentPageInfo.getPageNum());
        data.setTotal(commentPageInfo.getTotal());
        commentListVO.setData(data);

        commentListVO.getData().setList(new LinkedList<>());
        for (Comment comment : commentList) {
            CommentListVO.ListDTO listDTO = CopyModuleClassUtils.bean2vo(comment, CommentListVO.ListDTO.class);
            data.getList().add(listDTO);
        }

        return commentListVO.success();
    }

    private List<Comment> queryAllComments(CommentListBO commentListBO) {
        CommentExample commentExample = new CommentExample();
        CommentExample.Criteria criteria = commentExample.createCriteria();
        if (!objectIsEmpty(commentListBO.getUserId())){
            criteria.andUserIdEqualTo(commentListBO.getUserId());
        }
        if (!objectIsEmpty(commentListBO.getValueId())){
            criteria.andValueIdEqualTo(commentListBO.getUserId());
        }
        if (!objectIsEmpty(commentListBO.getSort() ) &&
                !objectIsEmpty(commentListBO.getOrder())){
            commentExample.setOrderByClause(commentListBO.getSort() + " " + commentListBO.getOrder());
        }
        criteria.andDeletedEqualTo(false);
        return commentMapper.selectByExample(commentExample);
    }


    @Override
    public CommentReplyVO reply(CommentReplyBO commentReplyBO) {

        CommentReplyVO commentReplyVO = new CommentReplyVO();
        // 先查询是否已有回复。如果有直接返回
        Comment comment =  commentMapper.selectByPrimaryKey(commentReplyBO.getCommentId());
        if (comment.getAdminContent() != null && !"".equals(comment.getAdminContent())){
            return new CommentReplyVO().failed();
        }

        // 没有回复的，进行更新
        Integer result = updateCommentAdminCounts(commentReplyBO);
        return new CommentReplyVO().success();
    }


    private Integer updateCommentAdminCounts(CommentReplyBO commentReplyBO) {
        Comment comment = new Comment();
        comment.setId(commentReplyBO.getCommentId());
        comment.setAdminContent(commentReplyBO.getContent());
        return commentMapper.updateByPrimaryKeySelective(comment);
    }


    @Override
    public CommentDeleteVO delete(CommentDeleteBO commentDeleteBO) {
        Integer result = deleteComment(commentDeleteBO);
        return new CommentDeleteVO().success();
    }

    @Override
    public int insertComment(CommentBO commentBO) {

        //获取订单商品的信息
        OrderGoods orderGoods = orderGoodsMapper.selectByPrimaryKey(commentBO.getOrderGoodsId());
        Order order = orderMapper.selectByPrimaryKey(orderGoods.getOrderId());


        //用comment对象接收参数，
        Comment comment = new Comment();

        comment.setValueId(orderGoods.getGoodsId());//此为商品id

        comment.setType((byte) 0);//type为0即为商品评论

        comment.setHasPicture(commentBO.isHasPicture());

        comment.setContent(commentBO.getContent());

        comment.setUserId(order.getUserId());

        comment.setHasPicture(commentBO.isHasPicture());

        comment.setAddTime(new Date());

        comment.setPicUrls(commentBO.getPicUrls());

        comment.setStar((short) commentBO.getStar());

        comment.setDeleted(false);//逻辑删除默认为false

        //插入评论数据
        int affected = commentMapper.insert(comment);

        //修改orderGoods表中comment为评论id
        orderGoodsMapper.updateComment(commentBO.getId(), commentBO.getOrderGoodsId());

       /* //改变order表中商品的可评价状态
        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectByOrderId(orderGoods.getId());
        boolean flag = false;
        for (OrderGoods orderGood : orderGoodsList) {
            //当所有商品都被评论时，将订单置为评论
            if (orderGood.getComment() == 0) {
                flag = true;
            }
        }*/
//       更新order中的comments为1
        /*if (!flag) {
            orderMapper.updateCommentStatus(order.getId());
        }*/
        if (affected == 1) {
            return 200;
        }
        return 404;

    }

    @Override
    public BasePageData queryWXAllComment(Integer valueId, Byte type, BaseParam baseParam) {
        MarketPageUtil.startPage(baseParam);

        List<WxCommentVo> commentVos = commentMapper.selectWXAllComment(valueId);

        return BasePageData.ok(commentVos);
    }

    @Override
    public CountCommentVo countComment(Integer valueId, Byte type) {
        CountCommentVo countCommentVo = new CountCommentVo();
        Integer allCount = commentMapper.selectAllCommentCount(valueId);
        Integer hasPicCount = commentMapper.selectHasPicCount(valueId);
        countCommentVo.setAllCount(allCount);
        countCommentVo.setHasPicCount(hasPicCount);
        return countCommentVo;
    }

    @Override
    public Comment addComment(Comment comment) throws CommentException {
        comment.setAddTime(new Date(System.currentTimeMillis()));
        comment.setUpdateTime(new Date(System.currentTimeMillis()));
        comment.setUserId(getUserId());
        int i = commentMapper.insertSelective(comment);
        if (i == 0) throw new CommentException();
        return comment;
    }

    private Integer deleteComment(CommentDeleteBO commentDeleteBO) {
        Comment comment = new Comment();
        comment.setId(commentDeleteBO.getId());
        comment.setUpdateTime(new Date());
        comment.setDeleted(true);
        return commentMapper.updateByPrimaryKeySelective(comment);
    }

    private Integer getUserId() {
        Subject subject = SecurityUtils.getSubject();
        User primaryPrincipal = (User) subject.getPrincipals().getPrimaryPrincipal();
        return primaryPrincipal.getId();
    }
}
